package edu.yuhf.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.yuhf.db.utils.JdbcTemplate;

import edu.yuhf.dao.iface.PermissionDao;
import edu.yuhf.domain.Permission;

public class PermissionJdbcDaoImpl implements PermissionDao {

	@Override
	public List<Permission> getPermissionByUser(int userId){
		String sql="select p.id,p.name,p.url,p.parentId,p.remark from users u left outer join userRole ur on u.id=ur.userid\r\n" + 
				" left outer join rolePermission rp on ur.roleid=rp.roleid \r\n" + 
				" left outer join permission p on p.id=rp.permissionid\r\n" + 
				" where u.id=1\r\n" + 
				"union\r\n" + 
				"select p.id,p.name,p.url,p.parentId,p.remark from permission p where id in(select distinct p.parentId from users u left outer join userRole ur on u.id=ur.userid\r\n" + 
				" left outer join rolePermission rp on ur.roleid=rp.roleid \r\n" + 
				" left outer join permission p on p.id=rp.permissionid\r\n" + 
				" where u.id=1)";
		List<Permission> list=JdbcTemplate.query(sql, (rs)->{
			List<Permission> list0=new ArrayList<>();
			try {
				while(rs.next()) {
					Permission p=new Permission(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5));
					list0.add(p);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return list0;
		}, new Object[] {userId});
		return list;
	}		
	
	public List<Permission> getPermissionAll() {
		String sql="select * from permission";
		List<Permission> list=JdbcTemplate.query(sql, (rs)->{
			List<Permission> list0=new ArrayList<>();
			try {
				while(rs.next()) {
					Permission p=new Permission(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5));
					list0.add(p);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return list0;
		}, new Object[] {});
		return list;
	}

	@Override
	public void getParentNode(List<Permission> list) {
		
	}
}
